<template>
  <n-tabs
      default-value="index"
      type="card"
      :tab-style="{padding:'7px',borderRadius:'15px'}"
      animated
      v-model:value="tabIndexValue"
      @update:value="updateTab"
      @close="closeTab"
  >
    <template #prefix>
      <n-button text>
        <n-icon>
          <i class="fa fa-angle-left" />
        </n-icon>
      </n-button>
    </template>
    <n-tab name="maintainOfCreditCard" >
      信用卡维护
    </n-tab>
    <n-tab v-for="(item,index) in tabs" :key="index" :name="item.key" closable>
      {{item.title}}
    </n-tab>
    <template #suffix>
      <n-button text>
        <n-icon>
          <i class="fa fa-angle-right" />
        </n-icon>
      </n-button>
    </template>
  </n-tabs>
</template>

<script>
import {useMessage} from "naive-ui";

export default {
  name: "TabPageTemplate",
  data(){
    return{
      message:useMessage(),
      tabIndexValue:'index',
      tabs:[
      ],
    }
  },
  watch:{
    '$route':function (){
      this.loadTab()
    }
  },
  methods:{
    loadTab:function (){
      const key=this.$route.meta.key;
      const url=this.$route.path;
      const title=this.$route.meta.title
      this.tabIndexValue=key;
      const tabs=this.tabs;
      if (key==='maintainOfCreditCard') return;
      if (tabs.findIndex(this.findKeyIndex)<0) {
        this.tabs.push({key,url,title});
      }else{
        this.tabIndexValue=key;
      }
    },
    updateTab:function (value){
      if (value === 'maintainOfCreditCard') {
        this.$router.push('/index/maintainOfCreditCard');
        return
      }
      const temp=this.tabs.find((item)=>item.key===value);
      this.$router.push(temp.url);
    },
    closeTab:function (value){
      const tabs=this.tabs;
      const key=this.$route.meta.key;
      const index=tabs.findIndex((item)=>item.key===value);
      if (index<0){
        this.message.warning('禁止删除的页面不存在');
        return;
      }
      this.tabs.splice(index,1);
      if (value!==key) return;
      this.$router.push('/index/maintainOfCreditCard');
    },
    findKeyIndex:function (item){
      return item.key===this.$route.meta.key;
    }
  },
  mounted() {
    this.loadTab()
  }
}
</script>

<style scoped>
  .n-tabs{
    width: calc(100% - 20px);
  }
</style>